package com.idroc.coelacanth.service.servant.bdb;

import java.io.File;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.idroc.coelacanth.config.GlobalConfigService;
import com.idroc.coelacanth.core.storage.Database;
import com.idroc.coelacanth.core.storage.DatabaseFactory;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;

/**
 * berkeley db 工厂
 * @author yuyoo (yuyoo4j@163.com)
 * @date 2009-12-15 下午01:37:33
 */
public final class BerkeleyDatabaseFactory implements DatabaseFactory {
	
	private static final Logger log = LoggerFactory.getLogger(BerkeleyDatabaseFactory.class);

	public static final String STORAGE_HOME = "storage_home";
	
	private String storageHome = null;

	private EnvironmentConfig envConfig = null;
	private Environment dbEnv = null; 
	
	public BerkeleyDatabaseFactory() {
		
		storageHome = GlobalConfigService.getInstance().getString(STORAGE_HOME);
		if ("".equals(storageHome)) {
			throw new IllegalArgumentException(String.format("没有配置存储主目录[%s]属性", STORAGE_HOME));
		}
		try { 
		    envConfig = new EnvironmentConfig();
		    envConfig.setAllowCreate(true);
		    envConfig.setSharedCache(true);
		    envConfig.setTransactional(true);
		    dbEnv = new Environment(new File(storageHome.trim()), envConfig);		    
		} catch (DatabaseException dbe) { 
			log.error("berkeley db 工厂 初始化异常.", dbe);
			throw new RuntimeException(dbe);
		} 
	}
	
	public Database getDatabase(String dbName) {
		
		return new BerkeleyDatabase(dbName, dbEnv); 
	}
}
